package com.tan.kotlintest.concurrent;

import com.tan.kotlintest.threadsynchronized.ThreadTool;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Administrator
 * <p>
 * 使用显示锁的范式
 *
 * (1) ReentrantLock 可重入锁
 *
 * (2) unlock()需要在finally中调用,防止程序奔溃中unlock()不了,导致死锁
 */
public class LockDemo {

    private int count = 0;
    private Lock lock = new ReentrantLock(true);

    public void incr() {
        lock.lock();
        try {
            count++;
            ThreadTool.sleep(1000);
            System.out.println("任务后: count: " + count);
        } finally {
            lock.unlock();
        }
    }

    public synchronized void incr2() {
        count++;
        incr2();
    }

    public static void main(String[] args) {
        LockDemo lockDemo = new LockDemo();
        DemoRunnable demoRunnable = new DemoRunnable(lockDemo);
        new Thread(demoRunnable).start();
        new Thread(demoRunnable).start();
        new Thread(demoRunnable).start();
    }

    private static class DemoRunnable implements Runnable {

        LockDemo demo;

        DemoRunnable(LockDemo demo) {
            this.demo = demo;
        }

        @Override
        public void run() {
            demo.incr();
        }

    }

}
